package com.gsta.ifishery.listener;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.gsta.ifishery.netty.thread.NameThreadFactory;
import com.gsta.ifishery.netty.thread.NettyServerThread;

/**
 * netty服务监听器 . <br>
 * 
 * @author hkb
 */
@WebListener
public class NettyServerListener implements ServletContextListener {

    /**
     * 线程池
     */
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 3, 10L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(3), NameThreadFactory.newNameThreadFactory("netty服务"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 此处仅需一个线程
        CountDownLatch latch = new CountDownLatch(1);
        executor.execute(NettyServerThread.newNettyServerThread(latch));
        try {
            latch.await(1, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

}
